const User = require('../models/users')
const bcrypt = require('bcryptjs')
const { generateToken } = require('../utils/jwt')

module.exports = {
  async login(body) {
    const { username, password } = body
    return new Promise(async (resolve, reject) => {
      try {
        const user = await User.findOne({ username })
        // 如果没有找到用户，则返回401错误
        if (!user) return resolve('User not found')
        // console.log(password, user.password)
        // 验证密码
        const isMatch = await bcrypt.compare(password, user.password)
        // console.log(111, isMatch)
        // 如果密码不匹配，则返回401错误
        if (!isMatch) resolve('Invalid password')
        // 生成JWT token
        const token = generateToken(user._id)
        // 存储token到用户对象（可选）
        user.token = token
        await user.save()
        resolve(user)
      } catch (error) {
        reject(error)
      }
    })
  }
}
